﻿using JMcms.Model;
using JMcms.Redis.Proxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JMcms.Web.UI
{
    public class RedisCacheHelper
    {
         
        /// <summary>
        /// 获取缓存集合
        /// </summary>
        public static List<object> GetCaches(string cpage,string pagesize,string keyname,out int totalcount)
        {
            int page = ToInt(cpage, 1), pageSize = ToInt(pagesize, 20);
            string keyName = keyname;
            List<string> keys = RedisManager.GetAllKeys();
            totalcount = keys.Count;
            if (!string.IsNullOrWhiteSpace(keyName))
            {
                keys = keys.Where(p => {
                    return p.Contains(keyName);
                }).ToList();
            }
            if (keys != null)
            {
                int startIndex = (page - 1) * pageSize, endIndex = page * pageSize - 1;
                Dictionary<string, object> dics = RedisManager.GetItems<object>(keys.Where((p, i) => {
                    return i >= startIndex && i <= endIndex;
                }).ToList());
                List<object> list = new List<object>();
                foreach (var key in dics)
                {
                    list.Add(new
                    {
                        Key = key.Key,
                        Value = key.Value,
                        Type = key.Value.GetType().FullName
                    });
                }
                //
               // WriteJSON(keys.Count, list, "");
                return list;
            }
            return null;
            //WriteJSON(0, null, "未获取到数据");
        }
        /// <summary>
        ///将日志文件添加到队列中
        /// </summary>
        public static void AddLog(string listid,string v)
        {
            RedisManager.AddLog(listid, v);
        }
        /// <summary>
        /// 添加集合
        /// </summary>
        public static int AddCatelogItem(string key, List<article_category> list)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return 0;
            }
            bool isSuccess = false;
            isSuccess = RedisManager.SetListEntity<article_category>(key, list);
            if (isSuccess)
            {
                return 1;
            }
            else {
                return 2;
            }
        }
    

        /// <summary>
        /// 添加项模拟后台登陆session
        /// </summary>
        public static int AddItem(string key, manager user,DateTime dt)
        {
              
            if (string.IsNullOrWhiteSpace(key))
            {

                return 0;
            }
            bool isSuccess = false;
            isSuccess = RedisManager.SetEntity<manager>(key,user,dt);
            if (isSuccess)
            {
                return 1;
            }
            else {
                return 2;
            }
        }
        public static manager getobj(string key)
        {
            manager o =RedisManager.GetEntitie<manager>(key);
            if (o!=null)
            {
                return o ;
            }
            else
            {
                return null;
            }

        }
          /// <summary>
        /// 添加项模拟后台登陆session
        /// </summary>
        public static int AddItem(string key, users user,DateTime dt)
        {
              
            if (string.IsNullOrWhiteSpace(key))
            {

                return 0;
            }
            bool isSuccess = false;
            isSuccess = RedisManager.SetEntity<users>(key,user,dt);
            if (isSuccess)
            {
                return 1;
            }
            else {
                return 2;
            }
        }
        /// <summary>
        /// 保存验证码
        /// </summary>
        /// <param name="key"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static int AddCode(string key, string code)
        {
            if (string.IsNullOrWhiteSpace(key))
            {

                return 0;
            }
            bool isSuccess = false;
            isSuccess = RedisManager.SetText(key, code);// 
            if (isSuccess)
            {
                return 1;
            }
            else {
                return 2;
            }

        }
        public static users getusers(string key)
        {
            users o =RedisManager.GetEntitie<users>(key);
            if (o!=null)
            {
                return o ;
            }
            else
            {
                return null;
            }

        }
        /// <summary>
        /// 保存普通字符串
        /// </summary>
        public static bool AddStr(string key, string value)
        {
          return  RedisManager.SetText(key, value);
        }
        /// <summary>
        /// 添加项
        /// </summary>
        public static string AddItem(string itemtype, string keyname, string zhi)
        {
            string itemType = itemtype, key = keyname, value = zhi;
            if (string.IsNullOrWhiteSpace(key))
            {
                return "键值不能为空";
            }
            bool isSuccess = false;
            switch (itemType)
            {
                case "totalcount":
                    isSuccess = RedisManager.SetText(key, value);

                    break;
                case "user":

                    break;
            }
            if (isSuccess)
            {
                return "添加成功";
            }
            else {
                return "添加失败";
            }
        }
        /// <summary>
        /// 获取字符串
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string gettotalcount(string key)
        {
            string o = RedisManager.GetText(key);
            return o;

        }

        /// <summary>
        /// 删除当前缓存项
        /// </summary>
        public static string RemoveCurrentItems(string key)
        {
           
            if (!string.IsNullOrEmpty(key))
            {
                RedisManager.Remove(key);
                return "删除成功";

            }
            return "删除失败";
        }

            /// <summary>
        /// 删除缓存项
        /// </summary>
        public static string RemoveCatelogListItems(string key)
        {
            List<string> list = RedisManager.GetAllKeys();
            List<string> keys = new List<string>();
            for (int i = 0; i < list.Count; i++)
            {
              string[] a= list[i].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (a.Length > 0)
                {
                    if (key == a[0])
                    {
                        keys.Add(list[i]);
                    }
                }
            }
           // string[] keys = keysz.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            if (keys.Count > 0)
            {
                RedisManager.RemoveAll(keys);
                return "删除成功";
            }
            return "删除失败";
        }
          /// <summary>
        /// 删除缓存项
        /// </summary>
        public static string RemoveListItems(string key)
        {
            List<string> list = RedisManager.GetAllKeys();
            List<string> keys = new List<string>();
            for (int i = 0; i < list.Count; i++)
            {
              string[] a= list[i].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (a.Length > 0)
                {
                    if (key == a[0] || a[0] == "link"+"0")
                    {
                        keys.Add(list[i]);
                    }
                }
            }
           // string[] keys = keysz.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            if (keys.Count > 0)
            {
                RedisManager.RemoveAll(keys);
                return "删除成功";
            }
            return "删除失败";
        }

        /// <summary>
        /// 删除缓存项
        /// </summary>
        public static string RemoveItems(string key,string chanel_name)
        {
            List<string> list = RedisManager.GetAllKeys();
            List<string> keys = new List<string>();
            for (int i = 0; i < list.Count; i++)
            {
              string[] a= list[i].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (a.Length > 0)
                {
                    if (key == a[0] || a[0] == chanel_name+"chaoge" || a[0] == chanel_name + "0")
                    {
                        keys.Add(list[i]);
                    }
                }
            }
           // string[] keys = keysz.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            if (keys.Count > 0)
            {
                RedisManager.RemoveAll(keys);
                return "删除成功";
            }
            return "删除失败";
        }

        /// <summary>
        /// 删除缓存项
        /// </summary>
        public static string RemoveItems(string key)
        {
            List<string> list = RedisManager.GetAllKeys();
            List<string> keys = new List<string>();
            for (int i = 0; i < list.Count; i++)
            {
                string aa = list[i].ToString();
                if (aa.IndexOf(key) > -1)
                {
                    keys.Add(list[i]);
                }
            }
            if (keys.Count > 0)
            {
                RedisManager.RemoveAll(keys);
                return "删除成功";
            }
            return "删除失败";
        }

        /// <summary>
        /// 向客户端输出JSON字符串
        /// </summary>
        /// <param name="code">响应码</param>
        /// <param name="data">响应数据</param>
        /// <param name="message">响应消息</param>
        public static void WriteJSON(int code, object data, string message)
        {
           // Response.Write("{" + string.Format("\"code\":{0},\"data\":{1},\"message\":\"{2}\"", code, ToJSON(data), message) + "}");
        }

        /// <summary>
        /// 将一个对象转成JSON字符串
        /// </summary>
        /// <param name="o">要转成的对象</param>
        /// <returns></returns>
        public static string ToJSON(object o)
        {
            //try
            //{
            //    var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
            //    return serializer.Serialize(o);
            //}
            //catch (Exception ex)
            //{

            //}
            return string.Empty;
        }

        /// <summary>
        /// 从请求中获取参数值
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <returns>返回从RequestForm或者Request.QueryString中获取的参数值</returns>
        public static string GetStringFromRequest(string name)
        {
            return "";//Request.Form[name] ?? Request.QueryString[name] ?? string.Empty;
        }

        /// <summary>
        /// 转换为整型
        /// </summary>
        /// <param name="text">要转换的文本</param>
        /// <param name="defaultValue">转换失败默认值</param>
        /// <returns></returns>
        public static int ToInt(string text, int defaultValue = 0)
        {
            int result = defaultValue;
            if (Int32.TryParse(text, out result))
            {
                return result;
            }
            return defaultValue;
        }
        /// <summary>
        /// 清空缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static void ClearCache()
        {
             RedisManager.Clear();
        }
        public static bool ContainsKey(string key)
        {
          return  RedisManager.ContainsKey(key);
        }
    }
}
